package com.toolmanrln.common.config;

import cn.hutool.core.util.StrUtil;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import io.swagger.models.Tag;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import springfox.documentation.service.Documentation;
import springfox.documentation.swagger2.mappers.ServiceModelToSwagger2MapperImpl;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 自定义Swagger API 排序
 * 方法分组tags命名格式，产品版本号-内容注释，例如：1.8.1-xxx
 * @author ToolMan.RLN
 * @since 2020-05-14 16:09
 */
@Component
@Primary
public class SwaggerSortConfig extends ServiceModelToSwagger2MapperImpl {

    @Override
    public Swagger mapDocumentation(Documentation from) {
        Swagger swagger = super.mapDocumentation(from);
        swagger.setPaths(mapApiListings(from.getApiListings()));
        //从方法中获取tags名称
        Map<String, Path> map = swagger.getPaths();
        List<String> list = new ArrayList<>();
        for (Map.Entry<String, Path> entry : map.entrySet()) {
            if (entry == null) {
                continue;
            }
            Path path = entry.getValue();
            if (path == null) {
                continue;
            }
            Operation operation = path.getPost();
            if (operation == null) {
                continue;
            }
            List<String> tagsList = operation.getTags();
            if (CollectionUtils.isEmpty(tagsList)) {
                continue;
            }
            for (int i = 0; i < tagsList.size(); i++) {
                if (StrUtil.isNotBlank(tagsList.get(i)) && tagsList.get(i).contains("-") && (tagsList.get(i).contains("1.")
                        || tagsList.get(i).contains("2.") || tagsList.get(i).contains("3."))) {
                    if (!list.contains(tagsList.get(i))) {
                        list.add(tagsList.get(i));
                    }
                }
            }
        }

        list.stream().distinct().collect(Collectors.toList());
        //创建tags
        List<Tag> newTags = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            newTags.add(new Tag().name(list.get(i)));
        }
        //自定义tag的排序
        Collections.sort(newTags, new Comparator<Tag>() {
            @Override
            public int compare(Tag left, Tag right) {
                String leftTag = left.getName().split("-")[0];
                String rightTag = right.getName().split("-")[0];
                if (StrUtil.equals(leftTag, rightTag)) {
                    return 0;
                }
                String[] leftNums = leftTag.split("\\.");
                String[] rightNums = rightTag.split("\\.");
                int position = 0;
                for (int i = 0; i < leftNums.length; i++) {
                    if (rightNums.length < i + 1) {
                        break;
                    }
                    position = Integer.compare(Integer.valueOf(leftNums[i]), Integer.valueOf(rightNums[i]));
                    if (position == 0) {
                        continue;
                    }
                    if (position != 0) {
                        return position;
                    }
                }
                if (position == 0) {
                    if (rightNums.length == leftNums.length) {
                        return position;
                    }
                    if (leftNums.length > rightNums.length) {
                        return 1;
                    }
                    if (leftNums.length < rightNums.length) {
                        return -1;
                    }
                }
                return position;
            }
        });
        List<Tag> tags = swagger.getTags();
        tags.addAll(newTags);
        swagger.setTags(tags);
        return swagger;
    }
}
